package com.cqc.googleplay.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.cqc.googleplay.utils.LogUtil;


public class HttpHelper {
	private static String tag = "HttpHelper";
	/**
	 * 进行get请求
	 * @param url
	 * @return 返回json数据
	 */
	public static String get(String url){
		String result = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		LogUtil.d(tag, "请求的url: "+url);
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);//http返回的数据
			if(httpResponse.getStatusLine().getStatusCode()==200){
				//请求成功
				HttpEntity httpEntity = httpResponse.getEntity();//获取响应体对象
				InputStream is = httpEntity.getContent();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];//1k的缓冲区
				int len = -1;//用来记录每次读取到的字节长度
				while((len=is.read(buffer))!=-1){
					baos.write(buffer, 0, len);
//					baos.flush();//字节输出流不用刷
				}
				//关闭流和链接
				is.close();
//				baos.close();//字节输出流不用关闭，因为它的close方法是空实现
				httpClient.getConnectionManager().closeExpiredConnections();//关闭闲置链接，及时释放资源
				
				result = new String(baos.toByteArray(),"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		LogUtil.d(tag, "服务器返回的result: "+result);
		return result;
	}
}
